#include "color_separate_in_range.h"

Color_Separate_In_Range::Color_Separate_In_Range(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("HSV+inRange实现色彩分离案例");
}


void Color_Separate_In_Range::dropEvent(QDropEvent *event){
    path = event->mimeData()->urls().at(0).toLocalFile();
    showColorSplit(path.toStdString().c_str());
}

void Color_Separate_In_Range::showColorSplit(const char *filePath){
    Mat src = imread(filePath);
    if(src.empty()){
        qDebug()<<"图片为空";
       return;
    }
    imshow("src",src);
    //将图片转HSV色彩空间
    Mat hsv;
    cvtColor(src,hsv,COLOR_BGR2HSV);
    Mat mask;//掩码遮罩
    //使用inRang过滤像素
    inRange(hsv,Scalar(15,30,32),Scalar(50,255,255),mask);
    imshow("result",mask);

    //执行形态学操作去除噪声
    Mat kernel = getStructuringElement(MORPH_RECT,Size(5,5),Point(-1,-1));
    morphologyEx(mask,mask,MORPH_OPEN,kernel,Point(-1,-1));
    imshow("morphologyEx",mask);

    //腐蚀

    dilate(mask,mask,kernel,Point(-1,-1),2);
    imshow("erode",mask);

    vector<vector<Point>> contours;
    vector<Vec4i> heri;

    //寻找最大外接矩形
    findContours(mask,contours,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
    double maxArea = contourArea(contours[0]);
    int index = 0;
    for(size_t i = 0;i<contours.size();i++){
        double area = contourArea(contours[i]);
        if(maxArea<=area){
            maxArea = area;
            index = i;
        }
    }
    Rect rect = boundingRect(contours[index]);
    Rect rect2 = Rect(rect.x,rect.y,rect.width,rect.width);
    rectangle(src,rect2,Scalar(0,0,255),2,LINE_8);
//    imshow("final Result",src);

    circle(src,Point(rect.x+rect.width/2,rect.y+rect.width/2),rect.width/2,Scalar(0,0,255),3,LINE_8);
    imshow("circle",src);


}
